package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1.把任务添加到数据库表
        Boolean status = addDataToDb(task);
        //2.添加任务到redis
        if (status) {
            addDataToRedis(task);
        }
        //3.返回任务的id

        return task.getTaskId();
    }

    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志
        Task task = updateDb(taskId, ScheduleConstants.EXECUTED);

        //删除redis的数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return false;
    }

    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        Task task = null;

        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if(StringUtils.isNotEmpty(json)){
            task = JSON.parseObject(json, Task.class);

            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
        }

        return task;
    }

    /**
     * 删除redis中的任务数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = logsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            logsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception taskid={}", taskId);
        }

        return task;

    }

    /**
     * 添加数据到redis
     *
     * @param task
     */
    private void addDataToRedis(Task task) {
        //1.获取当前时间和未来五分钟的时间

        long currentTimeMillis = System.currentTimeMillis();

        //获取未来五分钟的时间
        //初始化一个日历对象
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long futureTime = calendar.getTimeInMillis();
        //2.判断任务执行的时间- 如果是立即执行的，添加到list，如果是延迟执行的，添加到zset,超过五分钟的为其他数据，不处理
        if (task.getExecuteTime() <= currentTimeMillis) {
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() < futureTime) {
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库表
     *
     * @param task
     * @return
     */
    private Boolean addDataToDb(Task task) {
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);

        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

        int count = taskinfoMapper.insert(taskinfo);

        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, logs);

        logs.setStatus(ScheduleConstants.SCHEDULED);
        logs.setVersion(1);
        logs.setTaskId(taskinfo.getTaskId());
        logs.setExecuteTime(new Date(task.getExecuteTime()));

        int count1 = logsMapper.insert(logs);

        task.setTaskId(taskinfo.getTaskId());

        //两张表都分别新增了一条记录才能成功
        return count == 1 && count1 == 1;
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        log.info("未来数据定时刷新---定时任务");

        //1.获取所有未来数据的集合
        Set<String> futuresKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        //2.判断key里面是否有过期的
        if (null != futuresKeys && futuresKeys.size() > 0) {
            for (String futuresKey : futuresKeys) {
                Set<String> tasks = cacheService.zRangeByScore(futuresKey, 0, System.currentTimeMillis());
                if (null != tasks && tasks.size() > 0) {
                    String topicKey = ScheduleConstants.TOPIC + futuresKey.substring(futuresKey.indexOf("future_"));

                    //3.如果有过期的则删除，同时把数据添加到list集合
                    cacheService.refreshWithPipeline(futuresKey, topicKey, tasks);
                }
            }
        }
        cacheService.releaseLock("FUTURE_TASK_SYNC");
    }

    /**
     * 数据库任务同步到redis
     */
    @PostConstruct //对象一旦被创建，那么就会调用reloadData来完成对象的初始化
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        log.info("reloadData invoked...");
        //1.删除redis中所有的缓存数据
        clearCache();

        //2.查询执行时间小于未来5分钟的所有任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        //3.遍历任务并把任务添加到redis
        if (null != taskinfoList && taskinfoList.size() > 0) {
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);

                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addDataToRedis(task);
            }
        }

    }

    /**
     * 清楚缓存
     */
    private void clearCache() {
        Set<String> topicSet = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureSet = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicSet);
        cacheService.delete(futureSet);
    }
}
